package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.common.CustomException;
import com.reggie.entity.Category;
import com.reggie.entity.Dish;
import com.reggie.entity.Setmeal;
import com.reggie.mapper.CategoryMapper;
import com.reggie.service.CategoryService;
import com.reggie.service.DishService;
import com.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    //删除前需要判断
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    //根据id删除分类，删除之前需要进行判断

    @Override
    public void remove(Long id) {
//        添加查询条件 根据分类id查询  LambdaQueryWrapper
//        查询当前分类是否关联了菜品 如果关联了抛异常  要用到两个表
//        查询当前分类是否关联了套餐 如果关联了抛异常
        LambdaQueryWrapper<Dish> dslqw = new LambdaQueryWrapper<>();
        dslqw.eq(Dish::getCategoryId, id);//把传过来的id 与实体类的id做对比
        int dslqwCount = dishService.count(dslqw);
        if (dslqwCount > 0) {
            //抛出了一个异常
            throw new CustomException("当前分类下关联了菜品，不能删除");//声明并调用一个异常
        }

        LambdaQueryWrapper<Setmeal> sslqw = new LambdaQueryWrapper<>();
        sslqw.eq(Setmeal::getCategoryId, id);
        int ssqlwCount = setmealService.count(sslqw);
        if (ssqlwCount > 0) {
            throw new CustomException("当前分类下关联了套餐，不能删除");

        }
        super.removeById(id);

    }
}
